package ru.smc.hogwarts.servlets.rooms;

import java.io.IOException;
import java.util.List;

import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import ru.smc.hogwarts.classes.EMF;
import ru.smc.hogwarts.model.Room;
import ru.smc.hogwarts.model.Student;

public class RoomsDepopulate extends HttpServlet {
	private static final long serialVersionUID = 1L;
	private HttpSession session;
       
    public RoomsDepopulate() {
        super();
    }

	@SuppressWarnings("unchecked")
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		session = request.getSession(true);
    	request.setAttribute("user", (String)session.getAttribute("userFN")+" "+session.getAttribute("userLN"));
    	
    	session.setAttribute("servletName", getServletName());
		
    	long id = 0;
		
		try {
			id = Long.parseLong(request.getParameter("id"));
		} catch (NumberFormatException e) {}
    	
    	EntityManagerFactory emf = EMF.getInstance().getEMF();
    	EntityManager em = emf.createEntityManager();
    	
		Student student = em.find(Student.class, id);
		
		if (student == null) {
			request.getRequestDispatcher("/pages/error/error.jsp").forward(request, response);
		} else {	
			Room room = student.getRoom();
			int rid = room.getId();
			
			List<Student> students = em.createQuery("select p from Student p where p.room.id like '"+ rid +"'").getResultList();
			
			em.getTransaction().begin();
			
			if (students.size() > 0) {
				room.setFull(students.size()-1);
				student.setRoom(null);
			}
			
			em.getTransaction().commit();
			
			response.sendRedirect(request.getContextPath() + "/rooms/info?id="+rid);
		}

		em.close();
	}

	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		this.doGet(request, response);
	}

}
